//
//  ImageLoader.m
//  FunnyOfTheDay
//
//  Created by Giorgi Gioshvili on 12/3/10.
//  Copyright 2010 FSS. All rights reserved.
//

#import "ImageLoader.h"

@implementation ImageLoader

@synthesize url, isLoadingData, lastError, expectedContentLength, progressBar, receivedData;


- (NSError *) loadImage:(NSString*)_url withProgressBar:(UIProgressView*)_progressBar {
    
    //Initialize
    self.url = _url;
    self.progressBar = _progressBar;
    isLoadingData = true;

    //Start loading the image and monitor its progress
    self._startLoadingImage;

    while ( isLoadingData ) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    return lastError;
}

- (void) _startLoadingImage {    
    NSLog(@"Starting to load image: %@\n", url);
    
    // Create the request
    NSURLRequest * theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];
    
    // create the connection with the request and start loading the data
    NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        self.receivedData = [NSMutableData data];
    } else {
        lastError = [[NSError alloc] initWithDomain:@"ImageLoader" code:1001 userInfo:nil];
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
    NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
    /* Don't delete, very useful for server side problem debugging
    NSLog(@"HTTP Status Code: %d", [httpResponse statusCode]);
    for (id key in [httpResponse allHeaderFields]) {
        NSLog(@"key: %@, value: %@", key, [[httpResponse allHeaderFields] objectForKey:key]);
    }
    */
    self.expectedContentLength = httpResponse.expectedContentLength;
    [receivedData setLength:0];
    progressBar.progress = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData
    [receivedData appendData:data];
    double progressMade = ((double)[receivedData length])/((double)self.expectedContentLength);
    self.progressBar.progress = progressMade;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed! Error - %@", [error localizedDescription]);
    isLoadingData = false;
    lastError = [error copy];

    [connection release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);
    isLoadingData = false;
    
    [connection release];
}

- (void)dealloc {
    
    [url release]; //TODO figure out why does this command (uncommented) cause a coredump
    [progressBar release];
    [lastError release];
    [receivedData release];

    [super dealloc];

}

@end
